<template>
  <div class="wash-equipment">
    <!-- 设备状态概览 -->
    <el-row :gutter="20" class="status-overview">
      <el-col :span="6">
        <div class="status-card normal">
          <div class="status-icon">
            <el-icon><Tools /></el-icon>
          </div>
          <div class="status-info">
            <div class="status-number">{{ statusStats.normal || 0 }}</div>
            <div class="status-label">正常运行</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="status-card warning">
          <div class="status-icon">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="status-info">
            <div class="status-number">{{ statusStats.warning || 0 }}</div>
            <div class="status-label">需要维护</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="status-card error">
          <div class="status-icon">
            <el-icon><CircleClose /></el-icon>
          </div>
          <div class="status-info">
            <div class="status-number">{{ statusStats.error || 0 }}</div>
            <div class="status-label">故障停机</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="status-card maintenance">
          <div class="status-icon">
            <el-icon><Setting /></el-icon>
          </div>
          <div class="status-info">
            <div class="status-number">{{ statusStats.maintenance || 0 }}</div>
            <div class="status-label">维护中</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <el-row :gutter="20" align="middle">
        <el-col :span="16">
          <el-form :model="searchForm" inline>
            <el-form-item label="设备名称">
              <el-input 
                v-model="searchForm.name" 
                placeholder="请输入设备名称" 
                clearable 
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="设备类型">
              <el-select v-model="searchForm.type" placeholder="请选择" clearable>
                <el-option label="洗衣机" value="washer" />
                <el-option label="烘干机" value="dryer" />
                <el-option label="熨烫机" value="iron" />
                <el-option label="包装机" value="packer" />
              </el-select>
            </el-form-item>
            <el-form-item label="设备状态">
              <el-select v-model="searchForm.status" placeholder="请选择" clearable>
                <el-option label="正常" value="normal" />
                <el-option label="警告" value="warning" />
                <el-option label="故障" value="error" />
                <el-option label="维护中" value="maintenance" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8" style="text-align: right">
          <el-button type="primary" @click="handleAddEquipment">
            <el-icon><Plus /></el-icon>
            添加设备
          </el-button>
          <el-button type="success" @click="handleBatchMaintenance" :disabled="!selectedEquipment.length">
            <el-icon><Tools /></el-icon>
            批量维护
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 设备列表 -->
    <el-card class="equipment-list">
      <el-table
        v-loading="loading"
        :data="equipmentData"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="设备名称" min-width="150">
          <template #default="{ row }">
            <div class="equipment-name">
              <el-avatar :size="40" :src="row.image" shape="square">
                <el-icon><Tools /></el-icon>
              </el-avatar>
              <div class="name-info">
                <div class="name">{{ row.name }}</div>
                <div class="code">{{ row.code }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="设备类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ getTypeText(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="运行状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentTask" label="当前任务" min-width="150">
          <template #default="{ row }">
            <div v-if="row.currentTask" class="current-task">
              <div class="task-name">{{ row.currentTask.name }}</div>
              <el-progress 
                :percentage="row.currentTask.progress" 
                :stroke-width="4"
                :format="(percentage) => `${percentage}%`"
              />
              <div class="task-time">剩余: {{ row.currentTask.remainTime }}</div>
            </div>
            <span v-else class="no-task">空闲</span>
          </template>
        </el-table-column>
        <el-table-column prop="workTime" label="工作时长" width="120">
          <template #default="{ row }">
            {{ row.workTime }}小时
          </template>
        </el-table-column>
        <el-table-column prop="lastMaintenance" label="上次维护" width="120" />
        <el-table-column prop="nextMaintenance" label="下次维护" width="120">
          <template #default="{ row }">
            <span :class="{ 'text-warning': isMaintenanceDue(row.nextMaintenance) }">
              {{ row.nextMaintenance }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button link size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button 
              link 
              size="small" 
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 'running' ? '停止' : '启动' }}
            </el-button>
            <el-button link size="small" @click="handleViewHistory(row)">
              历史
            </el-button>
            <el-dropdown @command="(command) => handleMoreAction(command, row)">
              <el-button link size="small">
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="maintenance">维护记录</el-dropdown-item>
                  <el-dropdown-item command="schedule">排程管理</el-dropdown-item>
                  <el-dropdown-item command="report">故障报告</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除设备</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 设备详情对话框 -->
    <!-- <EquipmentDetailDialog
      v-model:visible="detailDialogVisible"
      :equipment="currentEquipment"
      @refresh="getEquipmentList"
    /> -->

    <!-- 维护记录对话框 -->
    <!-- <MaintenanceHistoryDialog
      v-model:visible="historyDialogVisible"
      :equipment-id="currentEquipmentId"
    /> -->

    <!-- 添加/编辑设备对话框 -->
    <!-- <EquipmentFormDialog
      v-model:visible="formDialogVisible"
      :equipment="currentEquipment"
      @refresh="getEquipmentList"
    /> -->

    <!-- 维护对话框 -->
    <!-- <MaintenanceDialog
      v-model:visible="maintenanceDialogVisible"
      :equipment="currentEquipment"
      @refresh="getEquipmentList"
    /> -->
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Tools,
  Warning,
  CircleClose,
  Setting,
  Search,
  Refresh,
  Plus,
  ArrowDown
} from '@element-plus/icons-vue'
import { equipment } from '@/api/wash/index'
// import EquipmentDetailDialog from './components/EquipmentDetailDialog.vue'
// import MaintenanceHistoryDialog from './components/MaintenanceHistoryDialog.vue'
// import EquipmentFormDialog from './components/EquipmentFormDialog.vue'
// import MaintenanceDialog from './components/MaintenanceDialog.vue'

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: ''
})

// 页面状态
const loading = ref(false)
const equipmentData = ref([])
const selectedEquipment = ref([])

// 分页
const page = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 状态统计
const statusStats = reactive({
  normal: 0,
  warning: 0,
  error: 0,
  maintenance: 0
})

// 对话框状态
const detailDialogVisible = ref(false)
const historyDialogVisible = ref(false)
const formDialogVisible = ref(false)
const maintenanceDialogVisible = ref(false)
const currentEquipment = ref(null)
const currentEquipmentId = ref(null)

// 获取设备列表
const getEquipmentList = async () => {
  try {
    loading.value = true
    
    const params = {
      page: page.current,
      size: page.size,
      ...searchForm
    }
    
    // 调用真实API获取设备列表
    const res = await getWashEquipmentList(params)
    
    if (res.code === 200) {
      equipmentData.value = res.data.records || []
      page.total = res.data.total || 0
      
      // 统计各状态设备数量
      calculateStatusStats(res.data.records)
    }
  } catch (error) {
    console.error('获取设备数据失败:', error)
    ElMessage.error('获取设备列表失败')
  } finally {
    loading.value = false
  }
}

// 计算状态统计
const calculateStatusStats = (data) => {
  const stats = {
    normal: 0,
    warning: 0,
    error: 0,
    maintenance: 0
  }
  
  data.forEach(item => {
    if (stats.hasOwnProperty(item.status)) {
      stats[item.status]++
    }
  })
  
  Object.assign(statusStats, stats)
}

// 搜索和重置
const handleSearch = () => {
  page.current = 1
  getEquipmentList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    type: '',
    status: ''
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = () => {
  getEquipmentList()
}

const handleCurrentChange = () => {
  getEquipmentList()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedEquipment.value = selection
}

// 状态相关方法
const getStatusType = (status) => {
  const types = {
    normal: 'success',
    warning: 'warning',
    error: 'danger',
    maintenance: 'info'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    normal: '正常',
    warning: '警告',
    error: '故障',
    maintenance: '维护中'
  }
  return texts[status] || '未知'
}

const getTypeText = (type) => {
  const texts = {
    washer: '洗衣机',
    dryer: '烘干机',
    iron: '熨烫机',
    packer: '包装机'
  }
  return texts[type] || '未知'
}

// 判断是否需要维护
const isMaintenanceDue = (nextMaintenanceDate) => {
  if (!nextMaintenanceDate) return false
  const today = new Date()
  const maintenanceDate = new Date(nextMaintenanceDate)
  const diffDays = Math.ceil((maintenanceDate - today) / (1000 * 60 * 60 * 24))
  return diffDays <= 7 // 7天内需要维护
}

// 操作处理
const handleAddEquipment = () => {
  currentEquipment.value = null
  formDialogVisible.value = true
}

const handleViewDetail = (row) => {
  currentEquipment.value = row
  detailDialogVisible.value = true
}

const handleViewHistory = (row) => {
  currentEquipmentId.value = row.id
  historyDialogVisible.value = true
}

const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status === 'running' ? 'idle' : 'running'
    const res = await updateEquipmentStatus(row.id, { status: newStatus })
    
    if (res.code === 200) {
      ElMessage.success('设备状态切换成功')
      getEquipmentList()
    }
  } catch (error) {
    ElMessage.error('设备状态切换失败')
  }
}

const handleMoreAction = (command, row) => {
  currentEquipment.value = row
  
  switch (command) {
    case 'maintenance':
      // 维护记录
      break
    case 'schedule':
      // 维护计划
      break
    case 'report':
      // 故障报告
      break
    case 'delete':
      handleDeleteEquipment(row)
      break
  }
}

const handleDeleteEquipment = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除此设备吗？删除后无法恢复！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteEquipment(row.id)
    if (res.code === 200) {
      ElMessage.success('设备已删除')
      getEquipmentList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除设备失败')
    }
  }
}

const handleBatchMaintenance = async () => {
  if (selectedEquipment.value.length === 0) {
    ElMessage.warning('请选择要维护的设备')
    return
  }
  
  try {
    const ids = selectedEquipment.value.map(item => item.id)
    const res = await updateEquipmentStatus(ids, { status: 'maintenance' })
    
    if (res.code === 200) {
      ElMessage.success('批量维护已安排')
      getEquipmentList()
    }
  } catch (error) {
    ElMessage.error('批量维护失败')
  }
}

// 生命周期
onMounted(() => {
  getEquipmentList()
})
</script>

<style lang="scss" scoped>
.wash-equipment {
  padding: 20px;
  
  .status-overview {
    margin-bottom: 20px;
    
    .status-card {
      display: flex;
      align-items: center;
      padding: 20px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      
      .status-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
        
        .el-icon {
          font-size: 24px;
          color: #fff;
        }
      }
      
      .status-info {
        .status-number {
          font-size: 28px;
          font-weight: bold;
          margin-bottom: 5px;
        }
        
        .status-label {
          font-size: 14px;
          color: #666;
        }
      }
      
      &.normal {
        .status-icon {
          background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
        }
        .status-number {
          color: #67c23a;
        }
      }
      
      &.warning {
        .status-icon {
          background: linear-gradient(135deg, #e6a23c 0%, #f1b340 100%);
        }
        .status-number {
          color: #e6a23c;
        }
      }
      
      &.error {
        .status-icon {
          background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
        }
        .status-number {
          color: #f56c6c;
        }
      }
      
      &.maintenance {
        .status-icon {
          background: linear-gradient(135deg, #909399 0%, #b1b3b8 100%);
        }
        .status-number {
          color: #909399;
        }
      }
    }
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .equipment-list {
    .equipment-name {
      display: flex;
      align-items: center;
      gap: 10px;
      
      .name-info {
        .name {
          font-weight: bold;
          margin-bottom: 2px;
        }
        
        .code {
          font-size: 12px;
          color: #666;
        }
      }
    }
    
    .current-task {
      .task-name {
        font-size: 12px;
        margin-bottom: 5px;
      }
      
      .task-time {
        font-size: 12px;
        color: #666;
        margin-top: 2px;
      }
    }
    
    .no-task {
      color: #999;
      font-style: italic;
    }
    
    .text-warning {
      color: #e6a23c;
      font-weight: bold;
    }
  }
  
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 